package com.sunmouse.toolkit.fragment.media;


import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.sunmouse.toollib.constants.Interaction;
import com.sunmouse.toollib.utils.FileUtils;
import com.sunmouse.toollib.utils.system.PermissionUtil;
import com.nereo.imageselector.MultiImageSelector;
import com.nereo.imageselector.MultiImageSelectorActivity;
import com.squareup.picasso.Picasso;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.fragment.BaseFragment;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class AlbumFragment extends BaseFragment {


    @BindView(R.id.select_pic_btn)
    Button selectPicBtn;
    @BindView(R.id.camera_btn)
    Button cameraBtn;
    @BindView(R.id.result_iv)
    ImageView resultIv;
    Unbinder unbinder;

    private static final int CAMERA = 4;
    private static final int ALBUM = 5;
    private File mTmpFile;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_album, container, false);
        unbinder = ButterKnife.bind(this, v);
        return v;
    }



    @Override
    public void init() {
        this.selectPicBtn.setOnClickListener(this);
        this.cameraBtn.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_pic_btn:
                selectImage(ALBUM);
                break;
            case R.id.camera_btn:
                takePhoto();
                break;
        }
    }


    /**
     * take photo
     */
    private void takePhoto() {
        if (!PermissionUtil.isPermitted(getActivity(), Interaction.Permissions.Camera)) {
            PermissionUtil.requestPermission(getActivity(), Interaction.Permissions.Camera, CAMERA);
        } else {
            openCamera();
        }
    }

    /**
     * open camera
     */
    private void openCamera() {
        mTmpFile = FileUtils.newFile(FileUtils.getStoragePath() + "/images", (int) (Math.random() * 100000) + ".jpg");
        Uri mUri;
        mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mUri = FileProvider.getUriForFile(getActivity(), "com.sunmouse.toolkit", mTmpFile);
        } else {
            mUri = Uri.fromFile(mTmpFile);
        }

        mIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(mIntent, CAMERA);


    }

    /**
     * select  image
     *
     * @param requestCode
     */
    private void selectImage(int requestCode) {
        if (!PermissionUtil.isPermitted(getActivity(), Interaction.Permissions.Camera)) {
            PermissionUtil.requestPermission(getActivity(), Interaction.Permissions.Camera, requestCode);
        } else {
            launchImageSelector(requestCode);
        }
    }

    /**
     * launch image selector
     *
     * @param requestCode
     */
    private void launchImageSelector(int requestCode) {
        MultiImageSelector.create()
                .showCamera(true)
                .single()
                .start(getActivity(), requestCode);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults == null || grantResults.length < 1) return;
        if (requestCode == CAMERA) {
            openCamera();
        } else if (requestCode == ALBUM) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                selectImage(5);
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (requestCode == ALBUM) {
            List<String> results = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            Uri uri = data.getData();
            Picasso.with(getActivity())
                    .load("file:///" + results.get(0))
                    .resize(100, 100)
                    .into(resultIv);
        }else if(requestCode==CAMERA){
            Picasso.with(getActivity())
                    .load("file:///" + mTmpFile)
                    .resize(100, 100)
                    .into(resultIv);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
